import { useState, useEffect, useRef } from "react";
import { useLocation } from "react-router-dom";
import { message, Input, Button, Popover } from "antd";
import { io, Socket } from "socket.io-client";
import { chatroomList, chatHistoryList } from "@api/chat";
import { addFavorite } from "@api/favorite";
import { getUserInfo } from "@/utils/index";

import EmojiPicker from "@emoji-mart/react";
import data from "@emoji-mart/data";

import "./index.less";

interface ChatRoom {
    id: number;
    name: string;
}
interface ChatHistory {
    id: number;
    content: string;
    type: number;
    chatroomId: number;
    senderId: number;
    createTime: Date;
    sender: UserInfo
}
interface UserInfo {
    id: number;
    username: string;
    nickName: string;
    email: string;
    createTime: Date;
    headPic: string
}
interface JoinRoomPayload {
    chatroomId: number;
    userId: number;
}
interface SendMessagePayload {
    sendUserId: number;
    chatroomId: number;
    message: Message;
}
interface Message {
    type: 'text' | 'image';
    content: string;
}

type Reply = {
    type: 'sendMessage',
    userId: number,
    message: ChatHistory
} | {
    type: 'joinRoom',
    userId: number
}

const addToFavorite = async (chatHistoryId: number)=>{
    try {
        await addFavorite(chatHistoryId);
        message.success('收藏成功');
    } catch (error: any) {
        message.error(error?.data?.message || '系统繁忙，请稍后重试');
    }
}

export function Chat() {
    const location = useLocation();
    const [roomList, setRoomList] = useState<Array<ChatRoom>>([]);
    const [chatHistory, setChatHistory] = useState<Array<ChatHistory>>([]);
    const [inputText, setInputText] = useState<string>("");
    const [roomId, setRoomId] = useState<number>();
    const socketRef = useRef<Socket>();

    const queryChatroomList = async () => {
        try {
            const resp: any = await chatroomList();
            setRoomList(resp.map((item: ChatRoom) => {
                return {
                    ...item,
                    key: item.id
                }
            }))
        } catch (error: any) {
            message.error(error?.data?.message || '系统繁忙，请稍后再试');
        }
    }
    const queryChatHistoryList = async (chatroomId: number) => {
        try {
            const resp: any = await chatHistoryList(chatroomId);
            setChatHistory(resp.map((item: ChatHistory) => {
                return {
                    ...item,
                    key: item.id
                }
            }))
        } catch (error: any) {
            message.error(error?.data?.message || '系统繁忙，请稍后重试');
        }
    }
    const sendMessage = (value: string) => {
        if (!value) return message.warning('消息不能为空');
        if (!roomId) return message.warning('请先选择一个聊天室发消息');

        const payload: SendMessagePayload = {
            sendUserId: getUserInfo().id,
            chatroomId: roomId,
            message: {
                type: 'text',
                content: value
            }
        }
        socketRef.current?.emit('sendMessage', payload);
    }

    useEffect(() => {
        queryChatroomList();
    }, []);
    // 解决刚加载聊天记录的时候，不会滚动底部的问题
    useEffect(() => {
        setTimeout(() => {
            document.getElementById('bottom-bar')?.scrollIntoView({ block: 'end' });
        }, 300);
    }, [roomId]);
    useEffect(() => {
        if (!roomId) return message.warning('没有选择聊天室，无法连接');
        const socket = socketRef.current = io('http://localhost:3005');
        socket.on('connect', function () {
            const payload: JoinRoomPayload = {
                chatroomId: roomId,
                userId: getUserInfo().id
            };
            socket.emit('joinRoom', payload);
            socket.on('message', (reply: Reply) => {
                if (reply.type === 'sendMessage') {
                    // 性能优化-每次将发送的消息返回，不再都查一次聊天记录
                    // queryChatHistoryList(roomId);
                    setChatHistory(chatHistory => {
                        return chatHistory ? [...chatHistory, reply.message] : [reply.message];
                    })
                    setTimeout(() => {
                        // 使调用scrollIntoView()的元素滚动到容器的可视区域（end:表示位于可视区底部）
                        document.getElementById('bottom-bar')?.scrollIntoView({ block: 'end' });
                    }, 300);
                }
            })
        });

        return () => {
            socket.disconnect();
        }
    }, [roomId]);
    useEffect(() => {
        if (location.state?.chatroomId) {
            setRoomId(location.state?.chatroomId);
            queryChatHistoryList(location.state?.chatroomId);
        }
    }, [location.state?.chatroomId]);


    return <div className="chat">
        <div className="chat_room-list">
            {
                roomList?.map(item => {
                    return <div className={item.id === roomId ? 'room-item room-item--selected' : 'room-item'} data-id={item.id} key={item.id} onClick={() => {
                        queryChatHistoryList(item.id);
                        setRoomId(item.id);
                    }}>{item.name}</div>
                })
            }
        </div>
        <div className="chat_message-list">
            {
                chatHistory?.map(item => {
                    return <div className={item.senderId === getUserInfo().id ? 'message-item from-me' : 'message-item'} data-id={item.id} key={item.id} onDoubleClick={()=>{addToFavorite(item.id)}}>
                        <div className="message-sender">
                            <img src={item.sender.headPic} alt="" />
                            <span>{item.sender.nickName}</span>
                        </div>
                        <div className="message-content">{item.content}</div>
                    </div>
                })
            }
            <div id='bottom-bar' key='bottom-bar'></div>
        </div>
        <div className="chat_message-input">
            <div className="message-type">
                <div className="message-type_item">
                    <Popover trigger="click" content={<EmojiPicker data={data} onEmojiSelect={(emoji: any) => {
                        console.log('aaaaaaaaa')
                        setInputText((inputText) => inputText + emoji.native)
                    }} />}>表情</Popover>
                </div>
                <div className="message-type_item">图片</div>
                <div className="message-type_item">文件</div>
            </div>
            <div className="message-area">
                <Input.TextArea className="message-area_box" value={inputText} onChange={(e) => { setInputText(e.target.value) }} />
                <Button className="message-area_btn" type="primary" onClick={() => {
                    sendMessage(inputText);
                    setInputText("");
                }}>发送</Button>
            </div>
        </div>
    </div>
}